package com.itheima.tlais_web_management.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlais_web_management.pojo.Result;
import com.itheima.tlais_web_management.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//过滤器
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class Loginfillter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断是否为登录请求
        //提取请求/接收对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        //1获取请求对象 url
        String url = req.getRequestURL().toString();
        log.info("url为{}",url);
        //2进行判断，看是否为登录操作
        if (url.contains("login")){
            log.info("正在进行登录操作，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3获取请求头中的令牌（token）
        String jwt = req.getHeader("token").toString();
        //4先判断令牌是否存在
        if (!StringUtils.hasLength(jwt)){
            log.info("查不到请求头，登录失败");
            Result error = Result.error("NOT_LOGIN");
            //使用alibaba社区JSON转换工具手动转换
            String jsonString = JSONObject.toJSONString(error);
            rep.getWriter().write(jsonString);
            return;
        }
        //5解析令牌 token
        try {
            //解析过程中令牌报错则表示令牌非法
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析失败，登录失败");
            Result error = Result.error("NOT_LOGIN");
            //使用alibaba社区JSON转换工具手动转换
            String jsonString = JSONObject.toJSONString(error);
            rep.getWriter().write(jsonString);
            return;
        }
        //6放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest, servletResponse);


    }




    }
